package app.controllers.mobileweb;

import app.Const;
import app.dtos.VoteDTO;
import app.interceptors.MobileWxMemberInterceptor;
import app.models.member.Member;
import app.models.sys.Settings;
import app.models.vote.Vote;
import app.models.vote.VoteCatetory;
import app.models.vote.VoteSetJoin;
import com.github.sog.config.StringPool;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.kit.Tuple;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.libs.AppFunc;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.jfinal.aop.Before;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * .
 * </p>
 *
 * @author liuhui
 * @version 1.0 14-5-15 下午9:41
 */
@Before(MobileWxMemberInterceptor.class)
public class VoteController extends BasicController {

    private static final Splitter PIP_SPLITTER = Splitter.on(StringPool.PIPE).omitEmptyStrings().trimResults();

    public void index() {
        int setId = getParaToInt(0, 0);
        if (setId > 0) {
            long memberId = getParaToLong(Const.MEMBER_PARAM, 0l);
            if (VoteSetJoin.dao.checkJoinByMember(memberId, setId)) {
                redirect("/mobileweb/vote/hasjoin");
                return;
            } else {
                final List<VoteCatetory> voteCatetories = VoteCatetory.dao.findCategoryBySet(setId);
                final List<Vote> voteList = Vote.dao.findBySet(setId);
                final Multimap<Long, Vote> maps = Multimaps.index(voteList, new Function<Vote, Long>() {
                    @Override
                    public Long apply(Vote input) {
                        return input.getNumber("category").longValue();
                    }
                });
                final Map<Long, Collection<Vote>> categoryVotes = maps.asMap();
                List<VoteDTO> voteDTOs = Lists.newArrayList();
                for (VoteCatetory voteCatetory : voteCatetories) {
                    final String title = voteCatetory.getStr("name");
                    final long id = voteCatetory.getNumber(AppFunc.TABLE_PK_COLUMN).longValue();
                    final Collection<Vote> votes = categoryVotes.get(id);
                    voteDTOs.add(new VoteDTO(title, (List<Vote>) votes));
                }
                setAttr("votes", voteDTOs);
            }

            setAttr("set", setId);
            render("index.ftl");
        } else {
            renderNull();
        }
    }

    public void hasjoin() {

    }

    public void submit() {
        long member = getParaToLong(Const.MEMBER_PARAM, 0l);
        if (member == 0) {
            renderNull();
            return;
        }
        String wx_no = getPara(Const.WX_PARAM);
        int set = getParaToInt("set");
        String data = getPara(Const.DATA_PARAM);
        if (Strings.isNullOrEmpty(data)) {
            renderError("请选择问题答案，谢谢");
        } else {
            Member member_record = Member.dao.findById(member);
            if (member_record == null) {
                renderJson(AjaxMessage.forbidden());
            } else {
                Date current = DateProvider.DEFAULT.getCurrentDate();
                // ,
                List<String> questions = AppFunc.COMMA_SPLITTER.splitToList(data);
                List<Tuple<String, String>> answers = Lists.newArrayList();
                for (String question : questions) {

                    // 解析答案 1|2-3: 1表示问题ID，2-3表示选项索引 | 分割
                    final List<String> answerAndIndex = PIP_SPLITTER.splitToList(question);
                    if (answerAndIndex.size() >= 2) {
                        final String vote = answerAndIndex.get(0);
                        final List<String> items = AppFunc.DASH_SPLITTER.splitToList(answerAndIndex.get(1));
                        for (String item : items) {
                            answers.add(new Tuple<String, String>(vote, item));
                        }
                    }
                }
                Vote.dao.memberVote(member_record, set, current, answers, data);
                Member.dao.optCurrency(member, true, NumberUtils.createDouble(Settings.vote()), "问卷调查赠送中南币");
                renderSuccess();
            }
        }
    }

    public void ok() {
    }
}
